﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Facebook.Web;
using Facebook;
using log4net;

namespace WebServiceFacebook
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class FBWebService : System.Web.Services.WebService
    {
        private static readonly log4net.ILog _logger = LogManager.GetLogger(typeof(FBWebService));
        [Serializable]
        public class PostMessage
        {
            public long PostMessageId { get; set; }
            public string AccessToken { get; set; }
            public string PageId { get; set; }
            public string Message { get; set; }
            public string Description { get; set; }
            public string Name { get; set; }
            public string Link { get; set; }
            public string Caption { get; set; }
            public string Picture { get; set; }
        }

        [WebMethod]
        public void PostMessageToPage(PostMessage message)
        {
            try
            {
                if (_logger.IsInfoEnabled)
                {
                    _logger.Info("PostMessageToPage() method invoked..");
                }

                var fb = new FacebookWebClient(message.AccessToken);
                dynamic me = fb.Get("me");

                string accessTokenPage = GetPageAccessToken(fb.AccessToken, message.PageId);
                var fbPages = new FacebookWebClient(accessTokenPage);

                var args = new Dictionary<string, object>();
                args["message"] = message.Message;
                args["description"] = message.Description;
                args["name"] = message.Name;
                args["link"] = message.Link;
                string postMessage = string.Format("/{0}/feed", message.PageId);
                fbPages.Post(postMessage, args);
            }
            catch (Exception ex)
            {
                _logger.Error("Error when posting message", ex);
                throw;
            }
        }

        [WebMethod]
        public void PostMessagesToPage(List<PostMessage> messages)
        {
            try
            {
                foreach (var message in messages)
                {
                    var fb = new FacebookWebClient(message.AccessToken);
                    dynamic me = fb.Get("me");

                    string accessTokenPage = GetPageAccessToken(fb.AccessToken, message.PageId);
                    var fbPages = new FacebookWebClient(accessTokenPage);

                    var args = new Dictionary<string, object>();
                    args["message"] = message.Message;
                    args["description"] = message.Description;
                    args["name"] = message.Name;
                    args["link"] = message.Link;
                    string postMessage = string.Format("/{0}/feed", message.PageId);
                    fbPages.Post(postMessage, args);

                    if (_logger.IsInfoEnabled)
                    {
                        _logger.Info("Message posted {0}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error when posting message", ex);
                throw;
            }
        }

        private string GetPageAccessToken(string accessToken, string pageId)
        {
            try
            {
                var fb = new FacebookClient(accessToken);

                var parameters = new Dictionary<string, object>();

                // Note that the access_token field is a non-default field and
                // must be requested explicitly via the fields URL parameter.
                // In addition, you must use a user access_token with the 
                // manage_pages permission to make this request, 
                // where the user is an administrator of the Page.
                parameters["fields"] = "access_token";
                var result = (IDictionary<string, object>)fb.Get(pageId, parameters);

                var pageAccessToken = (string)result["access_token"];

                return pageAccessToken;
            }
            catch (FacebookApiException ex)
            {
                // Note: make sure to handle this exception.
                throw;
            }
        }

    }
}